using System;
using System.Collections.Generic;
using System.Threading;

namespace PropertyExpression.ReactiveRelation.Test.Common
{
    public static class ConcurrentThreadsExecuter
    {
        public static void Execute(Action action)
        {
            var threads = new LinkedList<Thread>();
            var startSyncObject = new object();
            ThreadStart threadStart = 
                () =>
                    {
                        lock (startSyncObject)
                        {
                            Monitor.Wait(startSyncObject);
                        }
                        action();
                    };
            for (var i = 0; i < 5; i++)
            {
                var thread = new Thread(threadStart) {IsBackground = true};
                thread.Start();
                Thread.Sleep(0);
                threads.AddLast(thread);
            }

            Thread.Sleep(100);

            lock (startSyncObject)
            {
                Monitor.PulseAll(startSyncObject);
            }

            foreach (var thread in threads)
            {
                thread.Join();
            }
        }
    }
}